#include "notepad.h"
#include "ui_notepad.h"



Notepad::Notepad(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Notepad)
{
    ui->setupUi(this);
    connect(ui->newAction,&QAction::triggered,this,&Notepad::newActionSlot);
    connect(ui->openAction,&QAction::triggered,this,&Notepad::openActionSlot);
    connect(ui->saveAction,&QAction::triggered,this,&Notepad::saveActionSlot);
    connect(ui->helpAction,&QAction::triggered,this,&Notepad::helpActionSlot);
    connect(ui->backAction,&QAction::triggered,this,&Notepad::backActionSlot);
}

Notepad::~Notepad()
{
    delete ui;
}



void Notepad::newActionSlot()
{
    ui->textEdit->clear();
    this->setWindowTitle("新建文本文档.txt");

}


void Notepad::openActionSlot()
{
    QString fileName=QFileDialog::getOpenFileName(this,tr("选择一个文件"),QCoreApplication::applicationFilePath(),"*.cpp *.txt");

    if(fileName.isEmpty())
    {
        QMessageBox::warning(this,"警告","请选择一个文件");

    }else{
        //qDebug()<<filename;
        QFile file(fileName);
        file.open(QIODevice::ReadOnly);
        QByteArray ba=  file.readAll();
        ui->textEdit->setText(QString(ba));
        file.close();

    }
}


void Notepad::saveActionSlot()
{
    QString fileName=QFileDialog::getSaveFileName(this,"选择一个文件",QCoreApplication::applicationFilePath());

    if(fileName.isEmpty())
    {
        QMessageBox::warning(this,"警告","请选择一个文件");
    }
    else
    {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly);
        // ui->textEdit->toPlainText();
        QByteArray ba;
        ba.append((ui->textEdit->toPlainText()).toUtf8());
        file.write(ba);
        file.close();


    }
}

void Notepad::keyPressEvent(QKeyEvent *k)
{
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_S)
    {
        saveActionSlot();
    }

    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_O)
    {
        openActionSlot();
    }
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_N)
    {
        openActionSlot();
    }
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_H)
    {
        helpActionSlot();
    }
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_B)
    {
        backActionSlot();
    }

}



void Notepad::helpActionSlot()
{

    QString helpMessage = "欢迎使用 Notepad 文本编辑器！\n"
                          "以下是本编辑器的一些基本功能：\n"
                          "- 新建文件：通过菜单或快捷键快速创建新文档。\n"
                          "- 打开文件：打开已存在的文本文件进行编辑。\n"
                          "- 保存文件：保存您对当前文档的更改。\n"
                          "- 快捷键：支持常见的文本编辑快捷键，如 Ctrl+S 保存、Ctrl+O 打开等。\n"
                          "- 基本编辑功能：提供复制、粘贴、剪切、撤销等基本文本编辑操作。\n"
                          "如有更多疑问，请联系我或查看介绍视频。";

    ui->textEdit->setText(helpMessage);
}

void Notepad::backActionSlot()
{
    this->hide();
    Widget *w=new Widget;
    w->show();

}
